package com.css.fxfzdzzh.modules.basicData.service.impl;

import cn.hutool.core.util.PageUtil;
import com.css.fxfzdzzh.base.annotation.EntityValue;
import com.css.fxfzdzzh.base.exception.ShpFieldException;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.constants.GeomTypeEnum;
import com.css.fxfzdzzh.constants.YNEnum;
import com.css.fxfzdzzh.modules.basicData.entity.LandForm;
import com.css.fxfzdzzh.modules.basicData.entity.NaturalDensity;
import com.css.fxfzdzzh.modules.basicData.landslideSite.entity.FieldDesc;
import com.css.fxfzdzzh.modules.basicData.landslideSite.vo.TableVo;
import com.css.fxfzdzzh.modules.basicData.repository.impl.NaturalDensityRepository;
import com.css.fxfzdzzh.modules.basicData.vo.ListVo;
import com.css.fxfzdzzh.modules.basicData.vo.QueryByVersionParam;
import com.css.fxfzdzzh.util.PlatformDateUtils;
import com.css.fxfzdzzh.util.UUIDGenerator;
import com.css.fxfzdzzh.util.fileParsing.ParsingResult;
import com.css.fxfzdzzh.util.fileParsing.shp.ShpAnalyticUtil;
import com.css.fxfzdzzh.web.PlatformSessionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author Dbj
 * @date 2023年02月27日  15:42
 * 天然密度
 */
@Slf4j
@Service
public class NaturalDensityService {
    @Resource
    NaturalDensityRepository naturalDensityRepository;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private LandformService landformService;
    public RestResponse saveShpTemporaryData(ParsingResult shpData) {
        //生成临时版本号
        try {
            String dataVersion = UUID.randomUUID().toString().replaceAll("-", "");
            List<NaturalDensity> list = this.getList(shpData.getShpList(), dataVersion);
            if (list.size()>0){
                naturalDensityRepository.byShpBatchSave(list);
            }
            ListVo listVo = new ListVo("0", null, dataVersion, "天然密度", null, list);
            return RestResponse.succeed(listVo);
        } catch (ShpFieldException e) {
            log.error(e.getMessage() + "\n错误数据 > {}", shpData.getShpList());
            return RestResponse.fail(e.getMessage());
        } catch (IndexOutOfBoundsException e1) {
            return RestResponse.fail("字段数量不符合要求");
        }
    }
    private List<NaturalDensity> getList(List<List<Object>> shpList, String dataVersion) throws ShpFieldException{
        String userID = PlatformSessionContext.getUserID(); // 获取当前登录用户
        ArrayList<NaturalDensity> arrayList = new ArrayList<>();
        for (int i = 0; i < shpList.size(); i++) {
            List<Object> list = shpList.get(i);
            NaturalDensity obj = new NaturalDensity();
            //临时版本号
            obj.setDataVersion(dataVersion);
            //当前用户
            obj.setCreateUser(userID);
            obj.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            obj.setDelFlag(YNEnum.Y.toString());
            if("".equals(list.get(0))|| list.get(0)==null){
                throw new ShpFieldException("序号"+list.get(2)+"的空间数据有误");
            }else{
                obj.setGeom(ShpAnalyticUtil.checkGeomTypeOf(list.get(0).toString(), GeomTypeEnum.MULTIPOLYGON));
            }
            if("".equals(list.get(1))|| list.get(1)==null){
                throw new ShpFieldException("序号"+list.get(2)+"的天然密度不能为空");
            }else{
                obj.setDsnName(BigDecimal.valueOf(ShpAnalyticUtil.getDoubleVal(list.get(2).toString(), "天然密度", true)));
            }

            if("".equals(list.get(2))|| list.get(2)==null){
                throw new ShpFieldException("序号不能为空");
            }else{
                obj.setDsnNumber(ShpAnalyticUtil.getStringVal(list.get(2).toString(), "序号", true));
            }
            obj.setDsnId(UUIDGenerator.getUUID());
            arrayList.add(obj);
        }
        return arrayList;
    }

    public void deleteByVersion(String versionCode) {
        naturalDensityRepository.deleteByVersion(versionCode);
    }

    public void updateLs(String versionCode, String tempVersionCode) {
        naturalDensityRepository.updateLs(versionCode,tempVersionCode);
    }

    public void updateByVersion(String tempVersionCode, String versionCode, Integer dataRangeCountry) {
        naturalDensityRepository.updateByVersion(tempVersionCode,versionCode,dataRangeCountry);
    }

    public RestResponse getYwData(QueryByVersionParam queryByVersionParam) {
        List<NaturalDensity> list = naturalDensityRepository.getYwData(queryByVersionParam);
        if (queryByVersionParam.getPage() != null && queryByVersionParam.getRows() != null) {
            Long total = naturalDensityRepository.countByDataVersion(queryByVersionParam);
            return RestResponse.succeed(new HashMap<String, Object>() {{
                put("data", list);
                put("total", total);
                put("title",  getFieldTable());
                put("page", queryByVersionParam.getPage());
                put("rows", queryByVersionParam.getRows());
                put("totalPage", PageUtil.totalPage(total, queryByVersionParam.getRows()));
            }});
        } else {
            return RestResponse.succeed(new HashMap<String, Object>() {{
                put("data", list);
                put("title",  getFieldTable());
            }});
        }
    }

    public List<TableVo> getFieldTable(){
        Field[] declaredFields = NaturalDensity.class.getDeclaredFields();
        List<TableVo> list = new ArrayList<>();
        if(declaredFields.length>0){
            for(Field field : declaredFields){
                FieldDesc fieldDesc = new FieldDesc();
                field.setAccessible(true);
                EntityValue entityValue = field.getAnnotation(EntityValue.class);
                if(entityValue==null){
                    continue;
                }
                TableVo vo = new TableVo();
                vo.setLabel(entityValue.name());
                vo.setProp(field.getName());
                list.add(vo);
            }
        }
        return list;
    }
    public List<FieldDesc>  getFieldDesc() {
        Field[] declaredFields = NaturalDensity.class.getDeclaredFields();
        List<FieldDesc> list = new ArrayList<>();
        AtomicInteger sno = new AtomicInteger(1);
        if(declaredFields.length>0){
            for(Field field : declaredFields){
                FieldDesc fieldDesc = new FieldDesc();
                field.setAccessible(true);
                EntityValue entityValue = field.getAnnotation(EntityValue.class);
                if(entityValue==null){
                    continue;
                }
                String type = entityValue.type();
                String must = entityValue.must();
                String name = entityValue.name();
                String desc = entityValue.desc();
                fieldDesc.setType(type).setMust(must).setName(name).setDesc(desc).setSno(sno.get());
                sno.getAndAdd(1);
                list.add(fieldDesc);
            }
        }
        return list;
    }

    public List<NaturalDensity> getYwData(String versionCode, String geom) {
        return naturalDensityRepository.getYwData(versionCode, geom);
    }

  public static void main(String[] args) {
      Map<String,String> map = new HashMap<>();
      map.put("保军","保军_2");
      map.put("保中","保军_1");
      map.put("保伟","保军_3");
      map.entrySet().stream().sorted(Map.Entry.comparingByKey(String::compareTo)).
              collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue,newValue)->oldValue, LinkedHashMap::new)).
              forEach((K,V)-> System.out.println(K+":"+V));
  }

    public Integer getValidDataNum(String versionCode) {
        return naturalDensityRepository.getValidDataNum(versionCode);
    }

    public NaturalDensity getYwDetails(String id) {
        return naturalDensityRepository.getYwDetails(id);
    }
}
